import CommonModel from "@/components/common/CommonModel";
import { Image } from 'antd'
import React, {useRef, forwardRef, useImperativeHandle, useState} from "react";
import FileViewer from 'react-file-viewer';
import styles from './fileList.module.scss'

interface IModelRef {
    showModal: () => void
    handleCancel: (cb?: () => void) => void
    handleOk: (cb?: () => void) => void
}

interface IProps {
    btn: React.ReactNode
}

const FilePreview = forwardRef(({ btn }: IProps, ref) => {
    const modalRef = useRef(null)
    const [path, setPath] = useState<string>('')
    const [fileName, setFileName] = useState<string>('')
    const handleCancel = () => {
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        modalRef.current && (modalRef.current as IModelRef).handleCancel()
    }
    const showModal = (path: string, fileName: string) => {
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        modalRef.current && (modalRef.current as IModelRef).showModal()
        setPath(path)
        setFileName(fileName)
    }

    useImperativeHandle(ref, () => ({
        showModal: (path: string, fileName: string) => showModal(path, fileName)
    }))

    return (
        <CommonModel
            close={handleCancel}
            footer={<></>}
            ref={modalRef}
            title={'文件预览'}
            btn={btn}
            content={
                <div className={styles.preview}>
                    { (import.meta.env.VITE_ACCEPT_IMAGE as string).includes(fileName.split('.').pop() as string) ? <Image src={`/api${path}`} /> : null }
                    { (fileName.split('.').pop() as string).toUpperCase() === 'PDF' ? <iframe src={`${import.meta.env.VITE_BASE_URL + path}`} width='100%' height='500px'/> : null}
                    { !((import.meta.env.VITE_ACCEPT_IMAGE as string).includes(fileName.split('.').pop() as string) || (fileName.split('.').pop() as string).toUpperCase() === 'PDF') ? <FileViewer fileType={fileName.split('.').pop() as string} filePath={`/api${path}`}/> : null }
                </div>
            }
        />
    )
})

export default FilePreview